﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace PolePosition.v3.Desktop.Grids
{
    public partial class GridWorkQueue : GridBase
    {
        public GridWorkQueue()
            : base(Common.Enumerations.DataTypes.Custom)
        {
            InitializeComponent();
            dataGridViewWorkQueue.AutoGenerateColumns = false;
            ColumnRemedyStatusFK.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
        }

        private DataTable m_WorkqueueResults;
        private string m_XmissionKmlIds;
        private string m_DistributionKmlIds;

        private bool m_CombosBound = false;
        private void BindCombos()
        {
            if (Program.LookupTableData != null && !m_CombosBound)
            {
                ComboOptions.RemedyStatus(ColumnRemedyStatusFK);
            }
        }

        #region Asynch Processing (Implements IGridBase)

        public override void DoAsynchLoad(DoWorkEventArgs e)
        {
            dataGridViewWorkQueue.Invoke(new MethodInvoker(delegate() { dataGridViewWorkQueue.Enabled = false; }));

            DataSet _Data;
            _Data = PolePosition.v3.ServiceProxy.UtilityService.GetWorkQueueData(Program.UserSelections.UtilityId);
            
            //no paging so set to 1 so the bar enables if there are results
            if (_Data != null && _Data.Tables.Count > 0 && _Data.Tables[0].Rows.Count > 0)
                base.TotalItems = 1;
            else
                base.TotalItems = 0;

            e.Result = _Data;
        }

        public override void AsychLoadComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            base.AsychLoadComplete(sender, e);
            //do whatever needs to be done after asynch work complete (BackgroudWorker_RunWorkerCompleted)
            if (e.Cancelled)
            {

            }

            if (e.Error != null || e.Result == null)
            {
                //todo: create some sort of error dialog and use it here instead of messagebx
                DevComponents.DotNetBar.MessageBoxEx.Show("Error retrieving work queue data.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            m_WorkqueueResults = (e.Result as DataSet).Tables[0];
            this.dataGridViewWorkQueue.DataSource = bindingSourceGridData;
            FilterResults();
            
            this.dataGridViewWorkQueue.Visible = true;
            this.dataGridViewWorkQueue.Enabled = true;
        }

        public override void DoAsynchSave(DoWorkEventArgs e)
        {

        }

        public override void AsychSaveComplete(object sender, RunWorkerCompletedEventArgs e)
        {

        }
        
        public override void DoAsynchGetKml(DoWorkEventArgs e)
        {
            dataGridViewWorkQueue.Invoke(new MethodInvoker(delegate() { dataGridViewWorkQueue.Enabled = false; }));

            base.Kml = ServiceProxy.UtilityService.GetWorkqueueKML(m_XmissionKmlIds, m_DistributionKmlIds);
        }

        public override void AsychGetKmlComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            base.AsychGetKmlComplete(sender, e);
            this.dataGridViewWorkQueue.Enabled = true;

            if (e.Cancelled)
            {
                // not sure what to do
            }

            if (e.Error != null)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("Error retrieving map data.",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ShowKmlInMap();
        }
        
        #endregion

        #region Context Menu / Main Bar (Implements IGridBase)

        public override void DoSearch(Common.Enumerations.GridSearchByTpes searchBy, string searchBytext)
        {

        }

        public override void DoExportToExcel()
        {
            //can be overridden if needed
            base.saveFileDialog1.FileName = string.Format("Work Queue Export {0}.xls", DateTime.Today.ToString("MM_dd_yyyy"));
            if (base.saveFileDialog1.ShowDialog() != DialogResult.OK)
                return;

            base.StartProgressIndicator();

            //create a datatable of only displayed results to export
            DataTable _DisplayResults;
            _DisplayResults = m_WorkqueueResults.Clone();

            DataRowView _RowView;
            foreach (DataGridViewRow _Row in dataGridViewWorkQueue.Rows)
            {
                _RowView = _Row.DataBoundItem as DataRowView;
                _DisplayResults.Rows.Add(_RowView.Row.ItemArray);
            }

            //eliminate uneeded columns
            _DisplayResults.Columns.Remove("ProjectTypeFk");
            _DisplayResults.Columns.Remove("RemedyPrimaryKeyValue");
            _DisplayResults.Columns.Remove("RemedyStatusFK");
            _DisplayResults.Columns.Remove("WorkQueueType");
            _DisplayResults.Columns.Remove("KmlId");
            _DisplayResults.Columns.Remove("RemedyLastAction");
            _DisplayResults.Columns.Remove("SaveGuid");

            //rename others so that the column headers are nice in export
            _DisplayResults.Columns["VisitNumber"].ColumnName = "Visit #";
            _DisplayResults.Columns["InspectionResult"].ColumnName = "Inspection Result";
            _DisplayResults.Columns["ElectricalProblem"].ColumnName = "Electrical Problem";
            _DisplayResults.Columns["InspectionNotes"].ColumnName = "Inspection Notes";
            _DisplayResults.Columns["TopType"].ColumnName = "Top Type";
            _DisplayResults.Columns["AcquisitionDate"].ColumnName = "Discovered Date";
            _DisplayResults.Columns["RemedyStatusText"].ColumnName = "Remedy Status";
            _DisplayResults.Columns["RemedyAssigned"].ColumnName = "Assignment";
            _DisplayResults.Columns["RemedyNotes"].ColumnName = "Remedy Comments";
            _DisplayResults.Columns["RemedyResolvedDate"].ColumnName = "Closed Date";

            StopProgressIndicator();

            base.ShowExcelExportResults(_DisplayResults);
        }

        public override void DoEdit()
        {
            if (dataGridViewWorkQueue.SelectedRows == null)
                return;

            ShowEditor(true);
        }

        public override void DoOpen()
        {
            if (dataGridViewWorkQueue.SelectedRows == null)
                return;

            ShowEditor(false);
        }

        private void ShowEditor(bool editAllowed)
        {
            Editors.EditWorkQueueItem _Editor = null;

            DataRowView _RowView;
            _RowView = dataGridViewWorkQueue.SelectedRows[0].DataBoundItem as DataRowView;

            int? _RemedyPrimaryKeyValue;
            _RemedyPrimaryKeyValue = _RowView.Row.Field<int?>("RemedyPrimaryKeyValue");

            EntityLibrary.UtilityAssetXMissionStructurePolesCrossRemedyVendorInspectionVisitEntity _XmissionRemedy;
            EntityLibrary.VendorDistributionPoleRemedyEntity _DistributionRemedy;

            switch (_RowView.Row.Field<string>("WorkQueueType"))
            {
                case "Xmission":
                    _XmissionRemedy = new EntityLibrary.UtilityAssetXMissionStructurePolesCrossRemedyVendorInspectionVisitEntity()
                    {
                        Utility_Asset_XMissionStructure_Pole_CrossRemedy_Vendor_InspectionVisitId = _RemedyPrimaryKeyValue,
                        Vendor_InspVisit_XMissionStructure_PoleFK = _RowView.Row.Field<int?>("VisitNumber"),
                        RemedyStatusFK = _RowView.Row.Field<int?>("RemedyStatusFK"),
                        RemedyAssigned = _RowView.Row.Field<string>("RemedyAssigned"),
                        RemedyResolvedDate = _RowView.Row.Field<DateTime?>("RemedyResolvedDate"),
                        RemedyNotes = _RowView.Row.Field<string>("RemedyNotes")
                    };

                    _XmissionRemedy.AcceptChanges();
                    _Editor = new Editors.EditWorkQueueItem(editAllowed, _XmissionRemedy);

                    break;
                case "Distribution":

                    _DistributionRemedy = new EntityLibrary.VendorDistributionPoleRemedyEntity()
                    {
                        RemedyId = _RemedyPrimaryKeyValue,
                        PoleFk = _RowView.Row.Field<int?>("VisitNumber"),
                        RemedyStatusFK = _RowView.Row.Field<int?>("RemedyStatusFK"),
                        RemedyAssigned = _RowView.Row.Field<string>("RemedyAssigned"),
                        RemedyResolvedDate = _RowView.Row.Field<DateTime?>("RemedyResolvedDate"),
                        RemedyNotes = _RowView.Row.Field<string>("RemedyNotes")
                    };

                    _DistributionRemedy.AcceptChanges();
                    _Editor = new Editors.EditWorkQueueItem(editAllowed, _DistributionRemedy);

                    break;
                default:
                    break;
            }

            if (_Editor.ShowDialog() == DialogResult.OK)
            {
                //update the record in the grid
                if (_Editor.DataType == Common.Enumerations.DataTypes.WorkQueueXmission)
                {
                    _XmissionRemedy = _Editor.Data as EntityLibrary.UtilityAssetXMissionStructurePolesCrossRemedyVendorInspectionVisitEntity;

                    _RowView.Row.SetField<int?>("RemedyPrimaryKeyValue", _XmissionRemedy.Utility_Asset_XMissionStructure_Pole_CrossRemedy_Vendor_InspectionVisitId);
                    _RowView.Row.SetField<int?>("RemedyStatusFK", _XmissionRemedy.RemedyStatusFK);
                    _RowView.Row.SetField<string>("RemedyAssigned", _XmissionRemedy.RemedyAssigned);
                    _RowView.Row.SetField<DateTime?>("RemedyResolvedDate", _XmissionRemedy.RemedyResolvedDate);
                    _RowView.Row.SetField<string>("RemedyNotes", _XmissionRemedy.RemedyNotes);

                    //remedy status text
                    var _FindRemedy = (from remedy in Program.LookupTableData.RemedyStatus
                                       where remedy.RemedyStatusId == _XmissionRemedy.RemedyStatusFK
                                       select remedy.Name).FirstOrDefault();

                    _RowView.Row.SetField<string>("RemedyStatusText", _FindRemedy);

                }
                else if (_Editor.DataType == Common.Enumerations.DataTypes.WorkQueueDistribution)
                {
                    _DistributionRemedy = _Editor.Data as EntityLibrary.VendorDistributionPoleRemedyEntity;

                    _RowView.Row.SetField<int?>("RemedyPrimaryKeyValue", _DistributionRemedy.RemedyId);
                    _RowView.Row.SetField<int?>("RemedyStatusFK", _DistributionRemedy.RemedyStatusFK);
                    _RowView.Row.SetField<string>("RemedyAssigned", _DistributionRemedy.RemedyAssigned);
                    _RowView.Row.SetField<DateTime?>("RemedyResolvedDate", _DistributionRemedy.RemedyResolvedDate);
                    _RowView.Row.SetField<string>("RemedyNotes", _DistributionRemedy.RemedyNotes);

                    //remedy status text
                    var _FindRemedy = (from remedy in Program.LookupTableData.RemedyStatus
                                       where remedy.RemedyStatusId == _DistributionRemedy.RemedyStatusFK
                                       select remedy.Name).FirstOrDefault();

                    _RowView.Row.SetField<string>("RemedyStatusText", _FindRemedy);
                }
            }
            _Editor.Dispose();
        
        }

        public override void DoMapForGrid()
        {
            List<string> _XmissionKmlIds = new List<string>();
            List<string> _DistributionKmlIds = new List<string>();

            DataRowView _RowView;
            foreach (DataGridViewRow _Row in dataGridViewWorkQueue.Rows)
            {
                _RowView = _Row.DataBoundItem as DataRowView;

                switch (_RowView.Row.Field<string>("WorkQueueType"))
                {
                    case "Xmission":
                        _XmissionKmlIds.Add(_RowView.Row.Field<int?>("KmlId").ToString());
                        break;
                    case "Distribution":
                        _DistributionKmlIds.Add(_RowView.Row.Field<int?>("KmlId").ToString()); 
                        break;
                }
            }

            if (_XmissionKmlIds.Count() > 0)
                m_XmissionKmlIds = string.Join(",", _XmissionKmlIds.ToArray());
            else
                m_XmissionKmlIds = null;


            if (_DistributionKmlIds.Count() > 0)
                m_DistributionKmlIds = string.Join(",", _DistributionKmlIds.ToArray());
            else
                m_DistributionKmlIds = null;

            //clear KML type so it will reload
            Program.FormMain.MapControl.KMLType = PolePosition.v3.Common.Enumerations.DataTypes.None;
            StartAsynchGetKml();
        }

        public override void DoMapForRecord()
        {

        }

        public override bool ContextShowAllowed()
        {
            if (m_CancelContext)
                return false;

            if (dataGridViewWorkQueue.SelectedRows == null)
                return false;

            DataRowView _RowView;
            _RowView = dataGridViewWorkQueue.SelectedRows[0].DataBoundItem as DataRowView;

            double? _Latitude;
            _Latitude = _RowView.Row.Field<double?>("Latitude");

            double? _Longitude;
            _Longitude = _RowView.Row.Field<double?>("Longitude");

            if (_Latitude.HasValue)
                SelectedRowLatitude = decimal.Parse(_Latitude.ToString());
            else
                SelectedRowLatitude = null;

            if (_Longitude.HasValue)
                SelectedRowLongitude = decimal.Parse(_Longitude.ToString());
            else
                SelectedRowLongitude = null;

            return true;
        }

        #endregion

        public void ShowData(int utilityId)
        {
            base.DataKeyId = utilityId;
            BindCombos();
            dataGridViewWorkQueue.Visible = false;
            StartAsynchLoad();
        }

        private void FilterResults()
        {
            if (checkBoxItemShowComplete.CheckState == CheckState.Checked && (checkBoxItemShowRejected.CheckState == CheckState.Unchecked || checkBoxItemShowRejected.CheckState == CheckState.Indeterminate))
            {
                this.bindingSourceGridData.DataSource = m_WorkqueueResults;
            }
            else
            {
                DataView _Data = m_WorkqueueResults.DefaultView;
                _Data.RowFilter = (checkBoxItemShowComplete.CheckState == CheckState.Unchecked || checkBoxItemShowComplete.CheckState == CheckState.Indeterminate ? "IsNull(RemedyStatusText, '') <> 'Completed'": "1=1") + (checkBoxItemShowRejected.CheckState == CheckState.Checked ? "AND InspectionResult IN ('3-1', '3-2', '3-3', '3-4')": "");
                this.bindingSourceGridData.DataSource = _Data.ToTable();
            }
        }

        private void dataGridViewWorkQueue_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Right)
            //    m_columnheader = true;
        }

        private void dataGridViewWorkQueue_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            //if (e.ColumnIndex != dataGridViewWorkQueue.Columns[ColumnRemedyStatusFK.Index])
            //    return;

            //ColumnRemedyStatusFK.DisplayStyleForCurrentCellOnly = true;
            
            //dataGridViewWorkQueue.Columns[e.ColumnIndex]
        }

        private bool m_CancelContext;
        private void dataGridViewWorkQueue_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                m_CancelContext = true;
                return;
            }

            m_CancelContext = false;

            if (e.Button == MouseButtons.Right)
                dataGridViewWorkQueue.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
        }

        private void checkBoxItemShowComplete_CheckedChanged(object sender, DevComponents.DotNetBar.CheckBoxChangeEventArgs e)
        {
            FilterResults();
        }
    }
}
